# -*-Mode: tcl -*-
# ============================================================
# python.boost tmk module
# Copyright (C) 2010-2011 Yamauchi Hitoshi
# Sunday Researcher
# ============================================================

#
# assumed given strings
#
# python module name
#      MOD_CPP_SOURCE_BASE
#      ex.  ifgi_cpp_render_mod
# linking project list
#      PROJLIB_LIST
#      ex. { cpp/base cpp/scene }

#
# python module.so clean
#
target python_boost_clean ALWAYS_BUILD {
    set deletefilelist [glob -nocomplain *~]
    append deletefilelist " ${MOD_CPP_SOURCE_BASE}.so"
    puts -nonewline "file delete -- "
    foreach f ${deletefilelist} {
	file delete -force -- ${f}
	puts -nonewline "${f} "
    }
    puts ""
}
depend clean python_boost_clean


#----------------------------------------------------------------------
# write a file
proc write_file { data filename } {
    # open a file with "w"
    set fileId [open ${filename} "w"]
    puts -nonewline ${fileId} ${data}
    # close
    close ${fileId}
}

#----------------------------------------------------------------------

set PYTHON_INCPATH [exec python-config --include]

append cxx::FLAGS " -I ${PYTHON_INCPATH} -DPIC -shared -fexceptions -pthread"
append link::FLAGS " -DPIC -fPIC"

set COMPILE_OBJ_DIR [arch_name ${CODELEVEL}]

# set ABSOLUTE_CURRENT_DIR [pwd]
# puts $PROJROOT

set PROJLIB_OPT_STR {}
foreach bname $PROJLIB_LIST {
    # replace / to _, this is libbasename = cpp_base
    regsub -all {/} $bname {_} libbasename
    # e.g., libfilename = libcpp_base.so
    set libfilename "lib${libbasename}.so"
    # puts $libfilename

    # create linker options
    set PROJLIB_DIR ""
    append PROJLIB_DIR ${PROJROOT} "/" ${bname} "/" ${COMPILE_OBJ_DIR}

    # specified -rpath. But if you want to move the python cpp module
    # somewhere else, -rpath option should not be specified. And all
    # the .so location should be specified by LD_RUN_PAPH
    set RPATH_LD_OPT "-Wl,-rpath=${PROJLIB_DIR}"
    set LIBPATH_LD_OPT "-L${PROJLIB_DIR}"

    set PROJLIB_OPT {}
    # when -rpath needed
    lappend PROJLIB_OPT ${RPATH_LD_OPT}
    lappend PROJLIB_OPT ${LIBPATH_LD_OPT}
    lappend PROJLIB_OPT "-l$libbasename"
    # puts $PROJLIB_OPT

    append PROJLIB_OPT_STR $PROJLIB_OPT " "
}

set MOD_OBJ_FILE "$COMPILE_OBJ_DIR/${MOD_CPP_SOURCE_BASE}.o"

# We don't know the projlib's dependency, so just link twice.
set COMP_COM "g++ -DPIC -shared -fPIC -o ${MOD_CPP_SOURCE_BASE}.so ${MOD_OBJ_FILE} ${PROJLIB_OPT_STR} ${PROJLIB_OPT_STR} -lboost_python"

# puts ${python.boost::COMP_COM}
set BUILD_SH "build_mod.sh"
write_file ${COMP_COM} ${BUILD_SH}
puts "Created ${BUILD_SH}, please run it to build the python module."
# eval exec ${python.boost::COMP_COM}
